#include "stateupdate.h"
#include "enetwork.h"
#include "dbapp.h"
#include <QDate>
#include <QJsonDocument>
#include <QJsonObject>
#include "machineutil.h"
#include "mylogger.h"
#include "version.h"

using namespace ns_yht;

StateUpdate::StateUpdate()
{
}

StateUpdate::~StateUpdate()
{
}

StateUpdate *StateUpdate::instance()
{
    static StateUpdate *instance = nullptr;
    if (instance == nullptr)
    {
        instance = new StateUpdate();
    }
    return instance;
}

void StateUpdate::startHeartBeat()
{
    if (GLOG)
        GLOG->info("startHeartBeat......");
    QString url = QString("http://restapi.ehanghai.cn/xxyc-api/login/heartbeat?machineCode=%1&softwareCode=%2").arg(MachineUtil::machineCode(), SOFTWARECODE);
    QNetworkReply *reply = ENetwork::Get(url, "", "", false);
    connect(reply, &QNetworkReply::finished, this, [=]
            { requestHeartBeatFinished(reply); });
}

void StateUpdate::requestHeartBeatFinished(QNetworkReply *reply)
{
    if (ENetwork::checkReplyError(reply))
    {
        if (GLOG)
            GLOG->info("requestHeartBeat Finished 1. code:{} name:{}  result: false");
        // postUpdateLog(false);
        emit heartBeatFinished(false);
        return;
    }
    const QJsonDocument &jsonDocument = QJsonDocument::fromJson(reply->readAll());
    reply->deleteLater();
    if (!jsonDocument.isNull())
    {
        const QJsonObject &rootObj = jsonDocument.object();
        if (!rootObj.value("success").toBool())
        {
            if (GLOG)
                GLOG->info("requestHeartBeat Finished 2. code:{} name:{}  result: false");
            emit heartBeatFinished(false);
            return;
        }
        else
        {
            if (GLOG)
                GLOG->info("requestHeartBeat Finished 3. code:{} name:{}  reason:{} result: true");
            emit heartBeatFinished(true);
            return;
        }
    }
}
